<template>
  <div class="app-container">
    <el-input v-model="listQuery.menu_id" placeholder="请输入菜单编号" style="width:200px;margin-bottom: 10px;"
              clearable></el-input>
    <el-button type="primary" @click="getList" icon="el-icon-search"   style="margin-bottom: 10px;">
      搜索
    </el-button>

    <el-button   class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate()"
               style="margin-bottom: 10px;">
      添加
    </el-button>
    <el-button class="filter-item" style="margin-left: 0;margin-bottom: 10px;" type="primary" @click="cache()"> 缓存权限数据
    </el-button>

    <el-table :data="menuList" style="margin-bottom: 20px;" row-key="id" border
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="permission_id" label="权限ID"></el-table-column>
      <el-table-column prop="permission_name" label="权限名称"></el-table-column>
      <el-table-column prop="permission_key" label="权限key值"></el-table-column>
      <el-table-column prop="menu_id" label="菜单编号"></el-table-column>
      <el-table-column prop="menu_name" label="菜单名称"></el-table-column>
      <el-table-column prop="add_time" label="添加时间"></el-table-column>
      <el-table-column min-width="280" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>
            编辑
          </el-button>
          <!--          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage"
                    @pagination="getList"/>


    <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible"
               @close="handleDialogClose">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="120px"
               style="width: 400px; margin: 0 auto;">
        <el-form-item label="权限名称">
          <el-input v-model="form.permission_name" placeholder="请输入权限名称"/>
        </el-form-item>
        <el-form-item label='操作权限key值' prop="permission_key">
          <el-input v-model="form.permission_key" placeholder="请输入操作权限key值"/>
        </el-form-item>
        <el-form-item label='二级菜单ID' prop="menu_id">
          <el-input v-model="form.menu_id" placeholder="请从下面选择二级菜单ID" disabled style="margin-bottom: 10px;"/>
          <el-tree :data="menuListData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {permissionMenu, getMenu, saveMenu, updateMenu, cacheMenu} from '@/api/system/authentication'

import treeTable from '@/components/TreeTable'
import {validateCh} from '@/utils/validate'

// 常量title
const tempDesc = {
  'id': '',
  'parentId': '',
  'menu_key': '菜单key值',
  'menu_name': '名称',
  'level': '排序',
  'icon': '图标',
  'type': '类型',
  'status': '状态',
  'parentName': '上级菜单'
}

export default {
  components: {treeTable},
  data() {
    const _validateCh = (rule, value, callback) => {
      if (!!value && validateCh(value)) {
        callback(new Error('不能包含中文'))
      }
      callback()
    }
    return {
      expandAll: false,
      // expandAll: true, // 是否全部展开
      expandAllTitle: '展开全部',
      tempDesc: tempDesc,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      defaultProps: {
        children: 'children',
        label: 'menu_name'
      },
      columns: [
        {
          label: '菜单名称',
          key: 'title',
          width: 220,
          expand: true,
          align: 'left',
          headerAlign: 'center'
        },
        {
          label: '菜单key值',
          key: 'menu_key'
        },
        {
          label: tempDesc.type,
          key: 'type'
        },
        {
          label: '状态',
          key: 'status'
        },
        {
          label: tempDesc.icon,
          key: 'icon'
        },
        {
          label: '菜单层级',
          key: 'level'
        }
      ],
      menuList: [],
      menuTree: [],// 树形菜单
      menuListData: [],// 树形菜单
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      form: {
        'permission_id': undefined,
        'permission_name': undefined,
        'permission_key': undefined,
        'menu_id': undefined,
      },
      rules: {
        permission_name: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        permission_key: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        menu_id: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
      }
    }
  },
  created() {
    if (this.global_checkBtnPermission(['sys:menu:add', 'sys:menu:addsub', 'sys:menu:edit', 'sys:menu:delete'])) {
      this.columns.push({label: '操作', key: 'operation', width: 320})
    }
    this.getList()
    this.getMenu()
  },
  methods: {
    getList() {
      this.listLoading = true
      let urlData = '?';
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.menu_id) {
        urlData = urlData + `&menu_id=${this.listQuery.menu_id}`
      }

      permissionMenu(urlData).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total;

        this.listLoading = false
      })
    },
    getMenu() {
      getMenu().then(response => {
        this.menuListData = response.data
      })
    },
    handleNodeClick(data) {
      this.form.menu_id = data.menu_id

    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      if (!row) { // 一级菜单
        this.form.level = '1'// 默认一级菜单
        this.form.parentId = '0'
      }
      if (row) { // 子菜单
        this.form.level = parseInt(row.level) + 1
        this.form.parentId = row.id
        this.form.parentName = row.menu_name;
      }
    },
    handleUpdate(row) {
      this.form = []
      this.form.permission_id = row.permission_id
      this.form.permission_name = row.permission_name
      this.form.permission_key = row.permission_key
      this.form.menu_id = row.menu_id

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      let parentNode = this.findTreeNode(row.parentId)
      if (parentNode) {
        this.form.parentName = parentNode.menu_name
      }

      this.form = Object.assign({}, this.form)
    },
    handleDelete(row) {
      deleteMenu(row.id).then(response => {
        if (response.code === 0) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        }
      })
    },
    submitForm() {
      // this.form.parentName = undefined;
      this.$refs['dataForm'].validate(valid => {
        if (valid && this.dialogStatus === 'create') {
          saveMenu(this.form).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        } else if (valid && this.dialogStatus === 'update') {
          updateMenu(this.form).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          })
        }
      })
    },
    cache() {
      cacheMenu(this.form).then(response => {
        this.$notify({
          type: 'success',
          message: '操作成功',
          position: 'bottom-right',
          showClose: false,
          duration: 3000
        });
      })
    },
    findTreeNode(id) {
      let node = this._.find(this.menuList, {id: parseInt(id)})
      return node
    },
    handleExpand() {
      this.expandAll = !this.expandAll
      this.expandAllTitle = this.expandAll ? '折叠全部' : '展开全部'
    },
    resetForm() {
      this.form = {
        'permission_id': undefined,
        'permission_name': undefined,
        'permission_key': undefined,
        'menu_id': undefined,
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

